using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

using System.Xml.XPath;
using System.Xml;
using System.Xml.Schema;
using System.IO;

namespace VisualXPath
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        Dictionary<string, string> namespaces = new Dictionary<string, string>();
        
        private void XPathQuery_TextChanged(object sender, EventArgs e)
        {
            try
            {
                XPathQuery.BackColor = Color.White;
                XPathDocument doc = new XPathDocument(new StringReader(XmlDocument.Text));

                XPathNavigator nav = doc.CreateNavigator();
                
                XmlNamespaceManager nsManager = new XmlNamespaceManager(nav.NameTable);
                
                foreach (KeyValuePair<string, string> kvp in namespaces)
                	nsManager.AddNamespace(kvp.Key,kvp.Value);

                XPathNodeIterator iter = nav.Select(XPathQuery.Text,nsManager);

                StringBuilder sb = new StringBuilder();
                while (iter.MoveNext())
                {
                    sb.Append(iter.Current.Value + Environment.NewLine);
                }
                XPathResults.Text = sb.ToString();
                ErrDetails.SetToolTip(XPathQuery, "");
                this.Text = "XPath Visualiser";
            }
            catch (Exception ex)
            {
                XPathQuery.BackColor = Color.Red;
                ErrDetails.SetToolTip(XPathQuery, ex.Message);
                this.Text = "XPath Visualiser - " + ex.Message;
            }
        }

        private void openToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                DialogResult dr = openFileDialog1.ShowDialog();
                if (dr == DialogResult.OK)
                {
                    XmlDocument.Text = File.ReadAllText(openFileDialog1.FileName);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
        
        void ExitToolStripMenuItemClick(object sender, System.EventArgs e)
        {
        	Application.Exit();
        }
        

   		void AddClick(object sender, System.EventArgs e)
		{
			listView1.Items.Add(new ListViewItem(new string[] {nsName.Text ,nsUri.Text }));
			namespaces.Add(nsName.Text, nsUri.Text);
		}
    }
}
